<?php

	namespace org\tekuna\demo\weblog\manager;
	
	use org\tekuna\demo\weblog\model\Article;
	
	
	class ArticleManager extends AbstractEntityManager {
		
		const
			ENTITY_CLASS = 'org\\tekuna\\demo\\weblog\\model\\Article',
			TABLE_NAME = 'articles';

			
		public function getAllArticles() {
			
			return $this -> fetchAllEntities($this -> buildStatement('order by creationDate desc'));
		}
		
		
		public function getArticleArchives() {
			
			// special sqlite date functions for grouping
			$sQuery = 'select distinct '
			           . 'strftime("%Y", creationDate, "unixepoch") as year, '
			           . 'strftime("%m", creationDate, "unixepoch") as month, '
			           . 'count(*) as count '
			        . 'from articles '
			        . 'group by year, month';
			
			// run query
			$objStatement = $this -> objDbConn -> query($sQuery);
			
			// build result array
			$arrReturn = array();
			foreach ($objStatement as $arrRow) {
				
				$iTimestamp = mktime(0, 0, 0, $arrRow['month'], 1, $arrRow['year']);
				$arrReturn[$iTimestamp] = $arrRow['count'];
			}
			
			return $arrReturn;
		}
		
		
		public function getArchiveArticles($iYear, $iMonth) {
			
			$sWhere = ' where strftime("%Y", creationDate, "unixepoch") = :year'
			        . ' and strftime("%m", creationDate, "unixepoch") = :month';
			        
			$sOrder = ' order by creationDate';

			// prefix month with 0 to be comparable to %m in strftime
			$sMonth = sprintf('%02d', $iMonth);
			$arrParameters = array(':year' => $iYear, ':month' => $sMonth);
			
			return $this -> fetchAllEntities($this -> buildStatement($sWhere . $sOrder, $arrParameters));
		}
	}
